package com.zhj.util.state.chain;

import com.zhj.util.state.StateHandleException;
import com.zhj.util.state.enems.PreRegEventEnum;
import com.zhj.util.state.enems.PreRegStateEnum;

import java.util.*;

/**
 * @author zhj
 * @create 2024-04-18-14:45
 */
public class PreRegStateMachine {

    private Map<String, PreRegStateEnum> cache;

    private List<StateMachineTransaction> transactionList = Arrays.asList(
            StateMachineTransaction.builder()
                    .currentState(PreRegStateEnum.PRE_REG)
                    .event(PreRegEventEnum.REG)
                    .nextState(PreRegStateEnum.REG)
                    .build(),
            StateMachineTransaction.builder()
                    .currentState(PreRegStateEnum.PRE_REG)
                    .event(PreRegEventEnum.PATIENT_CANCEL)
                    .nextState(PreRegStateEnum.PATIENT_CANCEL)
                    .build(),
            StateMachineTransaction.builder()
                    .currentState(PreRegStateEnum.PRE_REG)
                    .event(PreRegEventEnum.HOSPITAL_CANCEL)
                    .nextState(PreRegStateEnum.HOSPITAL_CANCEL)
                    .build(),
            StateMachineTransaction.builder()
                    .currentState(PreRegStateEnum.REG)
                    .event(PreRegEventEnum.TREAT)
                    .nextState(PreRegStateEnum.TREAT)
                    .build(),
            StateMachineTransaction.builder()
                    .currentState(PreRegStateEnum.REG)
                    .event(PreRegEventEnum.REG_CANCEL)
                    .nextState(PreRegStateEnum.REG_CANCEL)
                    .build()
    );
    
    private PreRegStateEnum currentState;

    public PreRegStateEnum getCurrentState() {
        System.out.println("current state is : " + currentState);
        return currentState;
    }
    
    public PreRegStateMachine () {
        currentState = PreRegStateEnum.PRE_REG;
        cache = new HashMap<>();
        for (StateMachineTransaction stateMachineTransaction : transactionList) {
            String code = stateMachineTransaction.getCurrentState().toString() + stateMachineTransaction.getEvent().toString();
            cache.put(code, (PreRegStateEnum) stateMachineTransaction.getNextState());
        }
    }
    
    public void handleEvent(PreRegEventEnum event) throws Exception {
        PreRegStateEnum nextState = cache.get(currentState.toString() + event.toString());
        if (nextState == null) {
            throw new StateHandleException(currentState, event);
        }
        currentState = nextState;
    }
}
